<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use app\common\model\WxUser as WxUserModel;
use app\common\util\WechatThirdUtil;
/**
 * 通用上传接口
 * Class Upload.
 */
class Chatupload extends Controller
{
    private $wx_user;
    private $author_wx_user;
    private $wechatObj;
    protected $config;
    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->config = $this->wx_user->find();
    }

    /**
     * 通用图片上传接口.
     *
     * @return \think\response\Json
     */
    public function upload($file)
    {
        $config = [
            'size' => 2097152,
            'ext' => 'jpg,gif,png,bmp',
        ];

        $upload_path = str_replace('\\', '/', ROOT_PATH.'public/uploads');
        $save_path = '/uploads/';
        $info = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url' => str_replace('\\', '/', $save_path.$info->getSaveName()),
            ];
        } else {
            $result = [
                'error' => 1,
                'message' => $file->getError(),
            ];
        }

        return $result;
    }

    /*
     *上传资源返回media_id
     * */


    public function getMediaId(){
        if(Request::instance()->isPost()){
            $data = Request::instance()->post();
            $appid = $data['appid'];
            $file = $this->request->file('file');
            // 上传图片到本地upload
            $keyword_arr = $this->upload($file);
            if ($keyword_arr['error'] == 0) {
                $keyword = $keyword_arr['url'];
            } else {
                return false;
            }
            //  $wechatObj->uploadTempMaterial('.'.$data['auto_reply_img'], 'image');
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            $result = $wechatObj->uploadTempMaterial('.'.$keyword, 'image');
            if($result){
                return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $keyword, 'send_time' => time(),'media_id'=>$result['media_id']], JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['status' => -1, 'error' => '上传失败,请重试'], JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status' => 404, 'error' => '非法请求'], JSON_UNESCAPED_UNICODE);
        }

    }

    public function UnifiedUpload()
    {
        $file = $this->request->file('image');
        $result = $this->upload($file);

        return json($result);
    }

    /**
     * 通用图片上传接口.
     *
     * @return \think\response\Json
     */
    public function voiceUpload($file)
    {
        $config = [
            'size' => 2097152,
            'ext' => 'amr,speex,mp3,wav',
        ];

        $upload_path = str_replace('\\', '/', ROOT_PATH.'public/uploads');
        $save_path = '/uploads/';
        $info = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url' => str_replace('\\', '/', $save_path.$info->getSaveName()),
            ];
        } else {
            $result = [
                'error' => 1,
                'message' => $file->getError(),
            ];
        }

        return $result;
    }

    /**
     * 网络图片保存本地.
     *
     * @return \think\response\Json
     */
    public function saveChatImage($path)
    {
        $save_path = './uploads/'.date('Ymd').'/';
        if (!file_exists($save_path)) {
            mkdir($save_path, 0777, true);
        }
        $image_name = $save_path.base64_encode(date('H:i:s').rand(1000, 9999)).'.arm';
        $ch = curl_init($path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $img = curl_exec($ch);
        curl_close($ch);
        $fp = fopen($image_name, 'w');
        fwrite($fp, $img);
        fclose($fp);

        return ['path' => substr($image_name, 1)];
    }



}
